﻿using HuaHan.WorkTicket.Domain;
using HuaHan.WorkTicket.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkTicket.Application.Implementation
{
    public class BaseServiceImpl<T> where T:BaseEntity
    {
        #region Private Fields
        
        #endregion

        public BaseServiceImpl()
        {
        }

        public GenericRepository<T> Repository
        {
            get;
            set;
        }

        public UnitOfWork UnitOfWork
        {
            get;
            set;
        }


        public virtual List<T> GetAll()  
        {
            var result = Repository.GetAll().Where(c => c.IsDeleted == false).OrderByDescending(c => c.CreatedAt);
            return result.ToList();
        }

        public virtual void Add(T entity)
        {
            Repository.Add(entity);
            UnitOfWork.Commit();
        }

        public virtual void Delete(string id)
        {
            T entity = Repository.GetByKey(Guid.Parse(id));
            entity.IsDeleted = true;
            entity.UpdatedAt = DateTime.Now;
            Repository.Update(entity);
            UnitOfWork.Commit();
        }

        public virtual T GetItemByID(string id)
        {
            T entity = Repository.GetByKey(Guid.Parse(id));
            return entity;
        }

        public virtual void Update(T entity)
        {
            entity.UpdatedAt = DateTime.Now;
            Repository.Update(entity);
            UnitOfWork.Commit();
        }
    }
}
